#include <QtGui>

#include "renderarea.h"

RenderArea::RenderArea(QWidget *parent)
	: QWidget(parent)
	, traceCounter(0)
{
	setBackgroundRole(QPalette::Base);
    setAutoFillBackground(true);
	startTimer(50);

	water = new Water(4.0);
	ship = new Ship(water->waveVelocity, -0.05, 0.01, ShipCoord(0.0, 0.0, 0.0));
	box = new MathBox(water, ship);


	shipPath.moveTo(ship->coords.x + 250, -ship->coords.y + 250);
}

RenderArea::~RenderArea()
{
	delete box;
	delete ship;
	delete water;
}

QSize RenderArea::minimumSizeHint() const
{
    return QSize(200, 200);
}

QSize RenderArea::sizeHint() const
{
    return QSize(1000, 1000);
}

void RenderArea::drawShip(QPainter& painter)
{
	QPainterPath ship;

	ship.moveTo(-2.686, -10.855);
	ship.cubicTo(-1.917, -11.460, -1.150, -12.103, -0.214, -12.425);
	ship.cubicTo(0.471, -12.500, 1.058, -12.015, 1.618, -11.683);
	ship.cubicTo(3.509, -10.491, 4.405, -8.173, 4.500, -5.995);
	ship.cubicTo(4.487, 0.167, 4.500, 6.332, 4.492, 12.494);
	ship.cubicTo(1.496, 12.499, -1.496, 12.499, -4.492, 12.494);
	ship.cubicTo(-4.500, 6.332, -4.487, 0.167, -4.500, -5.995);
	ship.cubicTo(-4.455, -7.771, -3.791, -9.481, -2.686, -10.855);

	painter.drawPath(ship);
}

void RenderArea::paintEvent(QPaintEvent *event)
{
	QPainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing, true);

	pen.setStyle(Qt::DashLine);
	pen.setWidth(0);
	painter.setPen(pen);

	for(int i = 0; i != shipTrace.size(); ++i)
	{
		painter.scale(2.0,2.0);
		painter.translate(shipTrace[i].x + 250, -shipTrace[i].y+250);
		painter.rotate(shipTrace[i].course * 57.295779513082320876798154814105);
		drawShip(painter);
		painter.resetTransform();
	}

	painter.scale(2.0,2.0);
	painter.drawPath(shipPath);
	painter.resetTransform();


	pen.setStyle(Qt::SolidLine);
	pen.setWidth(2);
	painter.setPen(pen);
	painter.scale(2.0,2.0);
	painter.translate(ship->coords.x + 250, -ship->coords.y + 250);
	painter.rotate(ship->coords.course * 57.295779513082320876798154814105);
	drawShip(painter);
}

void RenderArea::timerEvent(QTimerEvent *event)
{
	if(traceCounter % 200 == 0)
	{
		shipTrace.push_back(ship->coords);
		traceCounter = 0;
	}

	shipPath.lineTo(ship->coords.x + 250, -ship->coords.y + 250);

	box->Step(0.05);
	++traceCounter;
	update();
}